/**
 * Author:LSP
 * Date:2020-12-07
 */

// 小组件配置
const widgetConfigs = {
    // 星期标题
    weekTitle: ['🙄 周日', '😪 周一', '😩 周二', '🤨 周三', '🤓 周四', '🤩 周五', '🥳 周六'],
    // 日期字体大小
    dayFont: Font.ultraLightSystemFont(12),
    // 日期文字颜色
    dayColor: new Color('000000', 1),
    // 今天日期文字颜色
    currDayColor: new Color('FF0000', 1),
    // 非本月日期文字颜色
    nonDayColor: new Color('BBBBBB', 1),
    // 农历数据缓存key
    lunarCacheKey: "calendar-medium-key",
    // 左侧日期字体
    calendarFont: Font.lightSystemFont(18),
    // 左侧日期颜色
    calendarColor: new Color('000000', 1),
    // 左侧星期几字体
    weekTitleFont: Font.lightSystemFont(14),
    // 左侧星期几颜色
    weekTitleColor: new Color('FF0000', 1),
    // 农历字体
    lunarFont: Font.regularSystemFont(14),
    // 农历颜色
    lunarColor: new Color('000000', 1),
}

//-------------------------------------
/**
 * 数字格式化
 * @param {number} num 
 */
function numFormatStr(num) {
    if (num > 0 && num < 10) {
        return `0${num}`
    } else {
        return `${num}`
    }
}

/**
 * 获取月份有多少天
 * @param {number} year 
 * @param {number} month 
 */
function getDays(year, month) {
    var date = new Date(year, month, 0)
    return date.getDate()
}

/**
 * 获取当前月份的1号是星期几(0~6)
 */
function getCurrentFirstDayWeek() {
    return new Date().getDay()
}

/**
 * 获取今天是星期几
 */
function getCurrDayWeekTitle() {
    var date = new Date()
    return widgetConfigs.weekTitle[date.getDay()]
}

/**
 * 在线获取农历信息
 */
async function getLunar(cacheKey) {
    let data = null

    try {
        const request = new Request("https://www.iamwawa.cn/home/nongli/ajax")
        const defaultHeaders = {
            "Accept": "*/*",
            "Content-Type": "application/json"
        }

        request.method = 'POST'
        request.headers = defaultHeaders

        request.addParameterToMultipart("type", "solar")
        request.addParameterToMultipart("year", year + "")
        request.addParameterToMultipart("month", month + "")
        request.addParameterToMultipart("day", currDay + "")

        data = await request.loadJSON()
        log(`农历数据：${data}`)

        // 存储缓存
        Keychain.set(cacheKey, JSON.stringify(data))
    } catch (e) {
        console.error(`网络请求POST出错：${e}`)
    }

    // 判断数据是否为空（加载失败）
    if (!data && Keychain.contains(cacheKey)) {
        // 判断是否有缓存
        let cache = Keychain.get(cacheKey)
        return JSON.parse(cache)
    }

    return data
}
//-------------------------------------


//-------------------------------------
// 小组件
// 日期
const thisDate = new Date()
// 年份
const year = thisDate.getFullYear()
// 月份
const month = thisDate.getMonth() + 1
// 日期
const currDay = thisDate.getDate()
// 格式化日期
const yearMonthText = year + "-" + numFormatStr(month)

// 上一个月的年份
let preMonthYear = null
// 上个月份
let preMonth = null
if (month == 1) {
    preMonthYear = year - 1
    preMonth = 12
} else {
    preMonthYear = year
    preMonth = month - 1
}
// 上个月有多少天
const preMonthDays = getDays(preMonthYear, preMonth)
// 当前月份有多少天
const currMonthDays = getDays(year, month)
// 当前月份1号是星期几
const currMonthFirstDay = getCurrentFirstDayWeek()
// 开始日期数字
const startNum = preMonthDays - currMonthFirstDay
// 总共42天
const totalDays = 42
// 日期数据分割
const dayRowArr = []
const dayRowArr1 = []
const dayRowArr2 = []
const dayRowArr3 = []
const dayRowArr4 = []
const dayRowArr5 = []
const dayRowArr6 = []
dayRowArr.push(dayRowArr1)
dayRowArr.push(dayRowArr2)
dayRowArr.push(dayRowArr3)
dayRowArr.push(dayRowArr4)
dayRowArr.push(dayRowArr5)
dayRowArr.push(dayRowArr6)

// 第一行日期填充
for (let index = 0; index < currMonthFirstDay + 1; index++) {
    // 上个月
    dayRowArr1.push(
        {
            num: startNum + index,
            font: widgetConfigs.dayFont,
            color: widgetConfigs.nonDayColor
        }
    )
}
let lastDayIndex = 0
for (let index = 0; index < 7 - currMonthFirstDay - 1; index++) {
    // 当前月
    lastDayIndex = index + 1
    let fontColor = widgetConfigs.dayColor
    if (lastDayIndex == currDay) {
        fontColor = widgetConfigs.currDayColor
    }
    dayRowArr1.push(
        {
            num: lastDayIndex,
            font: widgetConfigs.dayFont,
            color: fontColor
        }
    )
}

// 第二行日期填充
for (let index = 0; index < 7; index++) {
    lastDayIndex = lastDayIndex + 1
    let fontColor = widgetConfigs.dayColor
    if (lastDayIndex == currDay) {
        fontColor = widgetConfigs.currDayColor
    }
    dayRowArr2.push(
        {
            num: lastDayIndex,
            font: widgetConfigs.dayFont,
            color: fontColor
        }
    )
}

// 第三行
for (let index = 0; index < 7; index++) {
    lastDayIndex = lastDayIndex + 1
    let fontColor = widgetConfigs.dayColor
    if (lastDayIndex == currDay) {
        fontColor = widgetConfigs.currDayColor
    }
    dayRowArr3.push(
        {
            num: lastDayIndex,
            font: widgetConfigs.dayFont,
            color: fontColor
        }
    )
}

// 第四行
for (let index = 0; index < 7; index++) {
    lastDayIndex = lastDayIndex + 1
    let fontColor = widgetConfigs.dayColor
    if (lastDayIndex == currDay) {
        fontColor = widgetConfigs.currDayColor
    }
    dayRowArr4.push(
        {
            num: lastDayIndex,
            font: widgetConfigs.dayFont,
            color: fontColor
        }
    )
}

// 第五行
let nextMonthDayIndex = 0
if (lastDayIndex < currMonthDays) {
    let remainDays = currMonthDays - lastDayIndex
    remainDays = Math.min(7, remainDays)
    for (let index = 0; index < remainDays; index++) {
        lastDayIndex = lastDayIndex + 1
        let fontColor = widgetConfigs.dayColor
        if (lastDayIndex == currDay) {
            fontColor = widgetConfigs.currDayColor
        }
        dayRowArr5.push(
            {
                num: lastDayIndex,
                font: widgetConfigs.dayFont,
                color: fontColor
            }
        )
    }

    // 用下个月的日期填充
    if (remainDays < 7) {
        for (let index = 0; index < 7 - remainDays; index++) {
            nextMonthDayIndex = index + 1
            dayRowArr5.push(
                {
                    num: nextMonthDayIndex,
                    font: widgetConfigs.dayFont,
                    color: widgetConfigs.nonDayColor
                }
            )
        }
    }
}

// 第六行
if (lastDayIndex < currMonthDays) {
    let remainDays = currMonthDays - lastDayIndex
    remainDays = Math.min(7, remainDays)
    for (let index = 0; index < remainDays; index++) {
        lastDayIndex = lastDayIndex + 1
        let fontColor = widgetConfigs.dayColor
        if (lastDayIndex == currDay) {
            fontColor = widgetConfigs.currDayColor
        }
        dayRowArr6.push(
            {
                num: lastDayIndex,
                font: widgetConfigs.dayFont,
                color: fontColor
            }
        )
    }

    // 用下个月的日期填充
    if (remainDays < 7) {
        for (let index = 0; index < 7 - remainDays; index++) {
            nextMonthDayIndex = nextMonthDayIndex + 1
            dayRowArr6.push(
                {
                    num: nextMonthDayIndex,
                    font: widgetConfigs.dayFont,
                    color: widgetConfigs.nonDayColor
                }
            )
        }
    }
} else {
    // 用下个月的日期填充
    for (let index = 0; index < 7; index++) {
        nextMonthDayIndex = nextMonthDayIndex + 1
        dayRowArr6.push(
            {
                num: nextMonthDayIndex,
                font: widgetConfigs.dayFont,
                color: widgetConfigs.nonDayColor
            }
        )
    }
}


//-------------------------------------
const widget = new ListWidget()
widget.setPadding(0, 16, 0, 10)
const contentStack = widget.addStack()
contentStack.layoutHorizontally()

// 左侧stack
const leftStack = contentStack.addStack()
leftStack.layoutVertically()
leftStack.addSpacer()
// 日期
let monthText = leftStack.addText(numFormatStr(month) + "月" + currDay + "日")
monthText.font = widgetConfigs.calendarFont
monthText.textColor = widgetConfigs.calendarColor
monthText.leftAlignText()
// 星期几
leftStack.addSpacer(8)
let currWeekDayText = leftStack.addText(getCurrDayWeekTitle() + " ☞☞")
currWeekDayText.font = widgetConfigs.weekTitleFont
currWeekDayText.textColor = widgetConfigs.weekTitleColor
currWeekDayText.leftAlignText()
// 农历信息
leftStack.addSpacer(8)
let lunarInfo = await getLunar(widgetConfigs.lunarCacheKey)
let infoLunarText = lunarInfo.data.lunar
let infoSolarText = lunarInfo.data.solar
infoLunarText = infoLunarText.substring(12, infoLunarText.length)
let constellationText = lunarInfo.data.constellation
let lunarText = leftStack.addText(infoLunarText)
lunarText.font = widgetConfigs.lunarFont
lunarText.textColor = widgetConfigs.lunarColor
lunarText.leftAlignText()
//
leftStack.addSpacer()
///////////////////////////


// 右侧stack
contentStack.addSpacer()
const rightStack = contentStack.addStack()
rightStack.layoutVertically()
rightStack.addSpacer()

// 日期绘制
dayRowArr.forEach(row => {
    let rowStack = rightStack.addStack()
    rowStack.layoutHorizontally()
    row.forEach(item => {
        let itemStack = rowStack.addStack()
        itemStack.layoutHorizontally()
        itemStack.size = new Size(26, 0)
        let rowText = itemStack.addText(`${item.num}`)
        rowText.font = item.font
        rowText.textColor = item.color
        rowText.shadowColor = item.color
        rowText.shadowOffset = new Point(1, 1)
        rowText.shadowRadius = 1
        rowText.centerAlignText()
    })
    rightStack.addSpacer()
})

//-------------------------------------
widget.presentMedium()
Script.setWidget(widget)
Script.complete()
//-------------------------------------


